/******************************************************************
 * Created by: Goh Chee Hong                                       
 * Date of Creation: 1/1/2009

 * Status: Optimized and Finished
 *                                                                
 * Description: Send a library file
 ******************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Pbdms.BusinessLogic;
using Pbdms.NetworkDealer;
using Pbdms.Common.DataObject;
namespace Pbdms.BusinessLogic.FileTransfer
{
    public class LibraryTransferSenderGui : FileTransferGui
    {
        private Thread thTransfer = null;
        /// <summary>
        /// library item id
        /// </summary>
        private string itemID;
        /// <summary>
        /// file type   1 is file 2 is review file
        /// </summary>
        private string fileType;
        public LibraryTransferSenderGui()
        {

        }
        public LibraryTransferSenderGui(string keyID, string friendName, string itemID, string fileType, Network.NetworkController networkController, object connection)
            : base()
        {
            this.keyID = keyID;
            this.itemID = itemID;
            this.fileType = fileType;
            this.networkController = networkController;
            this.friendName = friendName;
            this.lblUser.Text = friendName;


            string filename = "";
            //retrieve the file
            if (fileType.Equals("1"))
            {
                Pbdms.Common.DataObject.FileInfo fileInfo = null;

                fileInfo = BusinessLogic.DataController.FileInfoController.create().getFileInfoObject(itemID);
                if (fileInfo != null)
                {
                    if (fileInfo.Existence == true)
                    {
                        if (fileInfo.Location.Equals(""))
                        {
                            filename = Common.Global.getLibFolder()+"\\"+fileInfo.FileName;
                        }
                        else
                        {
                            filename=fileInfo.Location+"\\"+fileInfo.FileName;
                        }
                    }
                }
            }
            else
            {
                Pbdms.Common.DataObject.Comment comment = null;
                comment = BusinessLogic.DataController.CommentController.create().getCommentFromDB(itemID);
                if (comment != null)
                {
                    if (!comment.ReviewFile.Equals(""))
                    {
                        filename = Common.Global.getLibFolder()+"\\"+comment.ReviewFile;
                    }
                }
            }
            this.lblStatus.Text = "Waiting for sending";
            this.authTcpClient = (AuthTcpClient)connection;
            if (!filename.Equals(""))
            {
                System.IO.FileInfo fInfo = new System.IO.FileInfo(filename);
                this.fileInfo = fInfo;
                this.lblDoc.Text = this.fileInfo.Name;
            }
            else
            {
                authTcpClient.Close();
            }

        }
        /// <summary>
        ///  start operation
        /// </summary>
        public override void start()
        {
            thTransfer = new Thread(new ThreadStart(send));
            thTransfer.IsBackground = true;
            thTransfer.Start();
        }
          /// <summary>
        /// send method
        /// </summary>
        private void send()
        {
            FileStream file = null;
            try
            {
                
                file= new FileStream(this.fileInfo.FullName, System.IO.FileMode.Open, System.IO.FileAccess.Read, FileShare.Read);
               
                NetworkMessage netMessage = new NetworkMessage();
                netMessage.TypeOfMessage = NetworkDealer.NetworkDealer.DOWNLOAD_REQUEST_GRANTED;
                //send size
                netMessage.MessageContent = this.fileInfo.Length.ToString();
                authTcpClient.sendMessage(netMessage);
                //start sending

               
                    int before = 0;
                    long rdby = 0;
                    long total = file.Length;
                    
                    byte[] buffed = null;
                    string currentDownload = Common.Global.GetFileSize(rdby);
                    string totalString = Common.Global.GetFileSize(total);
                    displayStatus( "Sending " + currentDownload + " of " + totalString);
                    while (rdby < total)
                    {
                        int length = 1024;
                        if (rdby + 1024 > total)
                        {
                            length = (int)(total - rdby);
                        }
                        buffed = new byte[length];
                        //Read from the File (len contains the number of bytes read)
                        int numBytesRead = 0;
                        while (length != numBytesRead)
                        {
                            // Read may return anything from 0 to numBytesToRead.
                            int n = file.Read(buffed, numBytesRead, length-numBytesRead);
                            numBytesRead += n;
                        }

                        //Write the Bytes on the Socket
                        authTcpClient.sendBytes(buffed);
                        //Increase the bytes Read counter
                        rdby = rdby + length;

                        int pc = (int)(((double)rdby / (double)total) * 100.00);
                        if (before != pc)
                        {
                            displayProgress(pc.ToString());
                            currentDownload = Common.Global.GetFileSize(rdby);
                            totalString = Common.Global.GetFileSize(total);
                            Thread.Sleep(100);
                        }
                        displayStatus("Sending " + currentDownload + " of " + totalString);
                        Thread.Sleep(100);
                        before = pc;
                       
                        
                    }
                    displayStatus("Finished sending");
                    Finished("");
                    authTcpClient.Close();
                




            }
            catch
            {
                try
                {
                    displayStatus("An unknown error occurred");
                    Finished("");
                }
                catch
                {

                }
            }
            finally
            {
                if (file != null)
                {
                    file.Close();
                }
                authTcpClient.Close();
                finished = true;
            }
        }
    }
}
